import React, { Component } from 'react';
import { Table , Checkbox, Button , Modal, Col , Row} from 'antd';
import axios from "axios";


import UserFormModal from "./UserFormModal"
import DateAPI from './DateAPI'
import UserSearchForm from './UserSearchForm'

let selectRowCounts = 0 ;    //记录选中的条数
var selectRows=[];           //选中的数据 []
let paramsEnd ={}            //查询最终参数 {}
class User extends Component {
    constructor(props) {
        super(props);
        this.state = { 
          data:[],
          totalCount:0,
          pageSize:10,
          current:1
         };
    }

  

    onPageChange=(page,pageSize)=>{
        // console.log(page,pageSize)
        this.getUser(page,pageSize,paramsEnd)
    
    }
    pageSizeChange=(current,pageSize)=>{
      // console.log(current,pageSize)
      this.getUser(current,pageSize,paramsEnd)
    }

    action=(value)=>{
        
        // console.log(value)  //   this  object
        alert("[ id:  '"+value.id+"'  ,   name:  '"+value.username+" ']")
    }


    componentDidMount(){
      this.getUser(1,10);
    }

    getUser=(page,pageSize,userParams)=>{
        let url = "http://localhost:8080/getAllUser";
        // userParams = JSON.parse(userParams)
        // userParams["page"]=page;
        // userParams["pageSize"]=pageSize;
        // let param  = JSON.stringify(userParams);
         //设置请求头  
        // axios.defaults.headers.post['Content-Type'] = 'application/json';
        // {responseType:'json',header:{
        //   'Content-Type': 'application/json;charset=utf-8',
        //   'Accept': 'application/json'
        // }}
        // userParams = JSON.parse(userParams)
        // userParams["page"]=page;
        // userParams["pageSize"]=pageSize;
        // let pp = JSON.stringify(userParams)
        // console.log(pp)
        // userParams = JSON.parse(pp)

        if(userParams!==undefined){
          userParams["page"]=page;
          userParams["limit"]=pageSize;
        
        }else{
          userParams ={
            page:page,
            limit:pageSize
          }
        }
        
        paramsEnd = userParams;
       
        console.log(paramsEnd)

        axios.get(url
            ,{params:paramsEnd}
          )
        .then((response)=> {
          // handle success
          // console.log(response.data.data);
          this.setState({
            current:page,
            pageSize:pageSize,
            data:response.data.data,
            totalCount:response.data.count
          
          })
        })
        .catch(function (error) {
          // handle error
          console.log(error);
        });
      }
      
      checkBoxSelect=(record, selected, selectedRows, nativeEvent)=>{
          if(selected){
            selectRowCounts++;
            selectRows.push(record);
            console.log(selectRows)
    
          }
          if(!selected){
      
            if(JSON.stringify(selectRows).indexOf(JSON.stringify(record))!==-1){

                let startIndex = selectRows.indexOf(record)
                selectRows.splice(startIndex,1)  //删除 数组中 该数据
                // console.log(selectRows)
            }
            // console.log(selectRows)
            selectRowCounts--;
          }
          // console.log(selectRowCounts)
          // console.log(selectRows)
          // alert("当前选中的数据："+JSON.stringify(record))
          // console.log(record)     //选中的当前行数据
          // console.log(selected)    //是否选中   true  or  false
          // console.log(selectedRows)  //所以选中的数据
            // selectRows
          // console.log(selectedRows.length)
      }

      onSelectAll=(selected, selectedRows, changeRows)=>{

        if(selected){
          selectRowCounts=selectRowCounts+changeRows.length
        }
        if(!selected){
          selectRowCounts=selectRowCounts-changeRows.length
        }
        console.log(selectRowCounts)
        // console.log(selected)    //是否全选  true  or  false
        // if(selected){
        //     alert("全选:"+selectedRows)
        // }else{
        //   alert("取消全选")
        // }
        // console.log(selectedRows)  //全选的数据
        // console.log(changeRows)    //当前页面  改变的数据  比如  当前页面有10条数据，开始选中9条，点击全选，此时这个返回开始未选中的那一条数据
      }
      delete=()=>{
          if(selectRows.length===0){
            Modal.confirm({
              title: '友情提示',
              content: '请先选中要删除的数据，再进行操作！',
              okText: '确认',
              cancelText: '取消',
              // onOk={this.hideModal},
              // onCancel={this.hideModal}
            });
            return false;
          }

          let url="http://localhost:8080/deleteByUsers";
          axios.post(url,selectRows)
          .then((res)=>{
            console.log(res)
            Modal.confirm({
              title: '友情提示',
              content: res.data.msg,
              okText: '确认',
              cancelText: '取消',
              // onOk={this.hideModal},
              // onCancel={this.hideModal}
            });
            selectRows.length=0;
            selectRowCounts=0;
            this.getUser(1,10,paramsEnd);
          })
          .catch(function (error) {
            // handle error
            console.log(error);
          });
      }

      openForm=(key)=>{       
          // console.log(this.refs.userFormModal)
          //修改操作
          if(key===2){
            if(selectRowCounts!==1){
              
                Modal.confirm({
                  title: '友情提示',
                  content: '您确定选中的是 1 条数据？',
                  okText: '确认',
                  cancelText: '取消',
                  // onOk={this.hideModal},
                  // onCancel={this.hideModal}
                });
                return false;
            }
            console.log(selectRows)
            let url = "http://localhost:8080/getUserById?id="+selectRows[0].id;
            axios.get(url)
            .then((response)=> {
              // handle success
              console.log(response)
              //表单回填
              this.refs.userFormModal.setState({
                visible: true,
              },()=>{
                  //新增操作
                  setTimeout(() => {
                    this.refs.userFormModal.backFill(response.data.data);  //清空表单
                  }, 200);
              })       
            })
            .catch(function (error) {
              // handle error
              console.log(error);
            });
        //新增
         }else{
            this.refs.userFormModal.setState({
              visible: true,
            },()=>{
                //新增操作
                setTimeout(() => {
                  this.refs.userFormModal.clearForm();  //清空表单
                }, 200);
            }) 
         } 
      }


      searchFormRest=()=>{
        console.log(123)
         this.formRef.props.form.resetFields()
      }
      searchFormSearch=()=>{
        let searchParams = this.formRef.props.form.getFieldsValue()
        console.log(searchParams)
        this.getUser(1,10,searchParams)
        //
      }

      hideModal = () => {
        this.setState({
          alertVisible: false,
        });
      }


    columns = [
        {
          title: 'ID', width: 100, dataIndex: 'id', key: '7', fixed: 'left',
        },
        {
          title: '姓名', width: 100, dataIndex: 'username', key: '8', fixed: 'left',
        },
        { title: '电话', width: 136,dataIndex: 'phone', key: '1' },
        { title: '地址', width:155, dataIndex: 'address', key: '2' },
        { title: 'e-mail',width:180 , dataIndex: 'email', key: '3' },
        { title: '部门', width:160 ,dataIndex: 'address', key: '4' },
        { title: 'create-time',width:160, dataIndex: 'createTime', key: '5' , render:(value,Object)=>{
            return DateAPI.format(value,'yyyy-MM-dd hh:mm:ss');
        } },
        { title: 'phone',  dataIndex: 'phone', key: '6' },
        // { title: '操作员',  dataIndex: 'updateUser', key: '9' },
        // { title: '候补地址',width:160 ,  dataIndex: 'address', key: '10' },
        // { title: 'e-mail' , dataIndex: 'email', key: '11' },
        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          width: 100,
          render: (value) => <a href="javascript:;" onClick={this.action.bind(this,value)}>action</a>,
        },
      ];


     
    render() {
        return (
            <div>

                <div>
                  <Row>
                   <UserSearchForm 
                   //获取子组件form属性及方法，必须使用这种写法
                    wrappedComponentRef={(searchForm) => this.formRef = searchForm}
                   />
                    <Col span={6} style={{ textAlign: 'left' }}>
                      <Button style={{ marginLeft: 8 ,marginTop: 4 }} type="primary" onClick={this.searchFormSearch}>查询</Button>
                      <Button style={{ marginLeft: 8 ,marginTop: 4}} onClick={this.searchFormRest}>
                          重置
                      </Button>
                     </Col>
                     </Row>
                </div>
                <div>
                
                    <Button type="primary" icon="plus-square" onClick={this.openForm.bind(this,1)}>新增</Button>
                
                    <Button style={{marginLeft:2,backgroundColor:'#20c299'}} type="primary" icon="edit" onClick={this.openForm.bind(this,2)}>修改</Button>
                
                    <Button style={{marginLeft:2}} type="primary" icon="delete" onClick={this.delete}>删除</Button>
              
                </div>
                
                <Table 
                rowKey={records=>records.id}   //Each record in table should have a unique `key` prop,or set `rowKey` to an unique primary key.
                columns={this.columns} 
                dataSource={this.state.data}  
                bordered={true}
                scroll={{ x: 1300 ,y: 540}}
                pagination={{
                  pageSize:this.state.pageSize,
                  current:this.state.current,
                  total:this.state.totalCount,
                  showSizeChanger:true,
                  onChange:this.onPageChange,   //上一页  下一页的回调
                  onShowSizeChange:this.pageSizeChange,   //改变页数的 回调
                  showQuickJumper:true,
                  size:"small"
                }}
                rowSelection={{
                    type:Checkbox,
                    onSelect:this.checkBoxSelect,
                    onSelectAll:this.onSelectAll
                }}
               
                />

                <UserFormModal 
                ref="userFormModal"
                run={this}
                />

            </div>
        );
    }
}

export default User;